from collections import defaultdict

def apriori(transactions, min_support):
    # Step 1: Calculate support for individual items
    itemsets = defaultdict(int)
    for transaction in transactions:
        for item in transaction:
            itemsets[frozenset([item])] += 1

    # Filter items that meet the min_support threshold
    itemsets = {item: count for item, count in itemsets.items() if count >= min_support}
    freq_itemsets = list(itemsets.keys())

    # Step 2: Generate larger itemsets from frequent itemsets
    while freq_itemsets:
        new_itemsets = defaultdict(int)
        for itemset in freq_itemsets:
            for transaction in transactions:
                if itemset.issubset(transaction):
                    new_itemsets[itemset] += 1

        # Filter itemsets that meet the min_support threshold
        new_itemsets = {item: count for item, count in new_itemsets.items() if count >= min_support}
        freq_itemsets = list(new_itemsets.keys())
        itemsets.update(new_itemsets)

    return list(itemsets.keys())

# Example usage
transactions = [
    ['milk', 'bread', 'butter', 'cheese'],
    ['bread', 'butter', 'jam'],
    ['milk', 'bread', 'butter', 'jam'],
    ['milk', 'bread', 'butter'],
    ['bread', 'butter', 'cheese'],
    ['bread', 'butter', 'cheese', 'jam'],
    ['milk', 'cheese', 'bread']
]
min_support = 3
result = apriori(transactions, min_support)
print("Frequent itemsets:", result)
